package com.ketai.appinfo.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ketai.appinfo.constant.Constantes;
import com.ketai.appinfo.param.ParamInsert;
import com.ketai.appinfo.param.ParamSelectByIf;
import com.ketai.appinfo.pojo.*;
import com.ketai.appinfo.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 *@Author 刘玉琼
 *@Time 2020-11-03
 *
 */
@RestController
public class DeveloperController {
    @Resource
    private DevUserServiceImpl devUserService;//开发者平台入口对象
    @Resource
    private AppCategoryService appCategoryService;//开发者平台级别分类入口对象
    @Resource
    private DataDictionaryService dataDictionaryService;//开发者平台状态、所属平台入口对象
    @Resource
    private AppInfoService appInfoService;//开发者平台基本信息
    @Resource
    private AppVersionService appVersionService;//开发者平台版本信息
    /**
     * 登录
     * @param devCode
     * @param devPassword
     * @param
     * @return
     */
    @GetMapping("login")
    public String getInvicationLogin(String devCode, String devPassword) {
        QueryWrapper queryWrapper= new QueryWrapper();
        queryWrapper.eq("devcode","test001");
        queryWrapper.eq("devPassword","123456");
        DevUser user=devUserService.getOne(queryWrapper);
        if (user==null){
            return "登录失败！ null";
        }
        return  "登录成功\n"+user.toString();
    }

    /**
     *注销
     * @param session
     * @return
     */
    @GetMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("devUserSession");
        return "redirect:/devlogin.jsp";
    }

    /**
     * 进入维护页面，显示app信息且条件查询
     * @return
     */
    @GetMapping("/toList")
    public String getList(ParamSelectByIf p, Model model){

        //绑定App一级级别别下拉框
        List<AppCategory> appCategory=appCategoryService.categoryLeverSelect();
        //model.addAttribute("categoryLevel1List",appCategory);

        //绑定状态下拉框
        List<DataDictionary> dictionariesStatus=dataDictionaryService.statusSelect();
       // model.addAttribute("statusList",dictionariesStatus);

        //绑定所属平台下拉框
        List<DataDictionary> flat=dataDictionaryService.flatSelect();
        //model.addAttribute("flatFormList",flat);

        //查询所有
        /*Page<UserList> userListPage=appInfoService.backUserFind(p);
        model.addAttribute("appInfoList",userListPage);*/
        //数据回显
        /*model.addAttribute("queryFlatformId",p.getQueryFlatformId());
        model.addAttribute("querySoftwareName",p.getQuerySoftwareName());
        model.addAttribute("queryStatus",p.getQueryStatus());
        model.addAttribute("queryCategoryLevel1",p.getQueryCategoryLevel1());
        model.addAttribute("queryCategoryLevel2",p.getQueryCategoryLevel2());
        model.addAttribute("queryCategoryLevel3",p.getQueryCategoryLevel3());
        model.addAttribute("pageIndex",p.getPageIndex());
        return "/developer/appinfolist";*/
        return "查询成功！"+appCategory.toString()+dictionariesStatus.toString()+flat.toString();
    }

    /**
     * 二级三级下拉框
     * @param pid
     * @return
     */
    @GetMapping("/category")
    @ResponseBody
    public String getcd(Integer pid){
        List<AppCategory> appCategorieThree=appCategoryService.categoryLever2Select(pid);
        String json = JSON.toJSONString(appCategorieThree);
        return json;
    }

    /**
     * 加载平台下拉框
     */
    @GetMapping("/getFlat")
    @ResponseBody
    public String getflat(){
        List<DataDictionary> flat=dataDictionaryService.flatSelect();
        String json=JSON.toJSONString(flat);
        return json;
    }

    /**
     * 加载一级分类下拉框
     */
    @GetMapping("/getLeve1")
    @ResponseBody
    public String getLeve1(Model model){
        List<AppCategory> appCategory=appCategoryService.categoryLeverSelect();
        model.addAttribute("categoryLevel1List",appCategory);
        String json=JSON.toJSONString(appCategory);
        return json;
    }

    /**
     * 进入新增页面
     * @return
     */
    @GetMapping("/toAdd")
    public String gettoAdd(Integer devid,Model model){
        model.addAttribute("devid",devid);
        return "/developer/appinfoadd";
    }

    /**
     * 实现新增
     */
    @GetMapping("/add")
    public String getAdd(ParamInsert p, MultipartFile logoImg, HttpServletRequest request){

        //  文件上传考虑   大小  文件类型   修改名称
        String realPath = null;
        String logoLocPath = null;

        // 判断是否上传文件
        if (!logoImg.isEmpty()) {
            // 获取上传文件夹的相对路径
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            String  locPath="D:/temp/";
            Long imgSize = 10485760L;
            // 判断文件是否过大
            if (logoImg.getSize() > imgSize) {
                request.setAttribute("fileUploadError", "* 上传文件过大！");
                return "上传文件失败";
            }
            // 判断文件的类型
            String fileName = logoImg.getOriginalFilename();
            String suffix = fileName.substring(fileName.indexOf(".") + 1);
            if (Arrays.asList(Constantes.IMGSUFFIX).contains(suffix)) {

                // 产生一个随机数
                String newName = UUID.randomUUID().toString();
                // 修改名称
                fileName = newName + "." + suffix;
                File file = new File(path, fileName);

                File locfile = new File(locPath, fileName);
                // 如果目录不存在  则创建
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                // 文件上传
                try {
                    logoImg.transferTo(file);
                    logoImg.transferTo(locfile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 给appInfo的图片路径属性赋值 使用相对路径
                // 文件数量大的时候 整个项目大 维护麻烦  页面不能直接获取到图片
                p.setLogopicpath(fileName);
                p.setLogolocpath(fileName);

                //tomcat 虚拟目录  图片存绝对路径
                Integer rst=appInfoService.devAppAdd(p);
                // OSS 第三存储
                if (rst>0) {
                    return "新增成功！";
                }
            }

        }
        appInfoService.devAppAdd(p);
        return "Success";
    }

    /**
     * 新增校验apkName
     *
     * @param APKName
     * @return
     */

   /* @GetMapping("/apkexist")
    @ResponseBody
    public String checkAPK(@RequestParam String APKName) {
        Map map = new HashMap();
        AppInfo appInfo = null;
        if (StringUtils.isEmpty(APKName)) {
            map.put("APKName", "empty");
        } else {
            appInfo = appInfoService.selectAPK(APKName);
            if (null != appInfo) {
                map.put("APKName", "exist");
            } else {
                map.put("APKName", "noexist");
            }
        }
        return JSONArray.toJSONString(map);
    }*/

    /**
     * 进入新增版本
     */
    @GetMapping("/appversionToadd")
    public String getAppversionToadd(Integer id, Model model, HttpSession session){
        List<AppVersion> appVersionList=appVersionService.selectByAppId(id);//历史版本信息
        AppInfo appInfo = appInfoService.selectByAppId(id);
        model.addAttribute("appname",appInfo.getSoftwarename());
        model.addAttribute("appVersionList",appVersionList);
        session.setAttribute("appInfoId",appInfo);
        return "/developer/appversionadd";
    }

    /**
     * 新增版本
     */
    @GetMapping("/appversionAdd")
    public String getAppversionAdd(AppVersion appVersion, MultipartFile logoImg, Integer appId, HttpServletRequest request){
        System.out.println("========="+appId);
        AppInfo appInfo = appInfoService.selectByAppId(appId);
        System.out.println("================"+appInfo.getApkname());
        String apkLocPath = null;
        String downloadLink = "/AppInfoSystem/statics/uploadfiles/";
        if (!logoImg.isEmpty()) {
            //获取上传文件夹的虚拟目录
            String locPath = "D:/temp/";
            //获得apk文件名称
            String filename = logoImg.getOriginalFilename();
            //获得后缀
            String apkType = filename.substring(filename.lastIndexOf(".") + 1);
            //修改名称
            String newName = appInfo.getApkname();
            filename = newName + "." + apkType;
            File localFile = new File(locPath, filename);
            //如果目录不存在，就创建
            if (!localFile.getParentFile().exists()) {
                localFile.getParentFile().mkdirs();
            }
            //文件上传
            try {
                logoImg.transferTo(localFile);
            } catch (Exception e) {
                request.setAttribute("fileUploadError", "上传失败！");
                return "新增版本失败";
            }
            downloadLink = downloadLink + filename;
            apkLocPath = locPath + filename;
            appVersion.setDownloadlink(downloadLink);
            appVersion.setApklocpath(apkLocPath);
            appVersion.setApkfilename(filename);
        }
        appVersionService.insert(appVersion);
        appInfoService.updateVersionId(appVersion.getId(), appId);
        return "新增版本success";
    }
    /**
     * 删除app以及所有版本信息
     *
     * @param id
     * @return
     */
    @GetMapping("/delapp")
    @ResponseBody
    public String delApp(@RequestParam Integer id) {
        boolean mark = appInfoService.devAppDel(id);
        Map map = new HashMap();
        if (mark) {
            map.put("delResult", "true");
        }
        if (!mark) {
            map.put("delResult", "false");
        }
        return JSONArray.toJSONString(map);
    }
}
